import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Message, MessageDocument } from '../entities/message.entity';

@Injectable()
export class MessagesService {
  constructor(
    @InjectModel(Message.name) private messageModel: Model<MessageDocument>,
  ) {}

  async create(messageData: {
    senderId: string;
    receiverId: string;
    type: string;
    content: string;
    isGroup?: boolean;
    groupId?: string;
    attachments?: string[];
  }): Promise<Message> {
    const message = new this.messageModel(messageData);
    return message.save();
  }

  async findByUser(userId: string, friendId: string, limit = 50, skip = 0) {
    return this.messageModel
      .find({
        $or: [
          { senderId: userId, receiverId: friendId },
          { senderId: friendId, receiverId: userId },
        ],
        isGroup: false,
        deletedAt: null,
      })
      .sort({ createdAt: -1 })
      .limit(limit)
      .skip(skip)
      .populate('senderId', 'username nickname avatar')
      .populate('receiverId', 'username nickname avatar')
      .exec();
  }

  async findByGroup(groupId: string, limit = 50, skip = 0) {
    return this.messageModel
      .find({
        groupId,
        isGroup: true,
        deletedAt: null,
      })
      .sort({ createdAt: -1 })
      .limit(limit)
      .skip(skip)
      .populate('senderId', 'username nickname avatar')
      .exec();
  }

  async markAsRead(messageId: string, userId: string) {
    return this.messageModel
      .findByIdAndUpdate(
        messageId,
        { $addToSet: { readBy: userId }, status: 'read' },
        { new: true }
      )
      .exec();
  }

  async getUnreadCount(userId: string) {
    return this.messageModel.countDocuments({
      receiverId: userId,
      readBy: { $nin: [userId] },
      deletedAt: null,
    });
  }

  async getRecentMessages(userId: string) {
    const messages = await this.messageModel
      .find({
        $or: [{ senderId: userId }, { receiverId: userId }],
        deletedAt: null,
      })
      .sort({ createdAt: -1 })
      .populate('senderId', 'username nickname avatar')
      .populate('receiverId', 'username nickname avatar')
      .exec();

    // 按对话分组并获取最新消息
    const conversations = new Map();
    
    messages.forEach(message => {
      const key = message.isGroup 
        ? `group_${message.groupId}` 
        : message.senderId._id.toString() === userId 
          ? `user_${message.receiverId._id}`
          : `user_${message.senderId._id}`;
      
      if (!conversations.has(key)) {
        conversations.set(key, {
          id: key,
          type: message.isGroup ? 'group' : 'user',
          lastMessage: message,
          unreadCount: 0,
        });
      }
    });

    return Array.from(conversations.values());
  }
}
